import TonWeb from "tonweb";
const {JettonMinter, JettonWallet} = TonWeb.token.jetton;
 import {beginCell, toNano} from '@ton/ton'
import { Address } from "@ton/core";
//引入全局变量
const ENV = import.meta.env

/**
 * ERC转账
 * @param tonConnectUI UI对象
 * @param fromAddress 出账地址
 * @param amount 转账金额 USDT/个
 * @param orderId 订单ID
 * @returns {Promise<*|null>}
 */
export const ercTransfer = async (tonConnectUI,fromAddress,amount,orderId) => {
    //USDT payment
    console.log("🚧 Jetton payment")
    const tonweb = new TonWeb();
    const jettonMinter = new TonWeb.token.jetton.JettonMinter(tonweb.provider, {address: ENV.VITE_ERC_TOKEN /* USDT token address */});
    console.log(jettonMinter);
    const jettonMinterAddress = await jettonMinter.getJettonWalletAddress(new TonWeb.utils.Address(fromAddress));
    console.log(jettonMinterAddress.toString(true))
    const jettonWallet = new TonWeb.token.jetton.JettonWallet(tonweb.provider, {
        address: jettonMinterAddress
    });
    const tonFee = '50000000' //多了就会自动退回的手续费

    const seqno = Date.now()
    const comment = new Uint8Array([... new Uint8Array(4), ... new TextEncoder().encode(orderId)]);
    const jettonBody = {
        queryId: seqno,
        //10000 表示0.01  10000*10*10 = 1USDT
        jettonAmount: '10000' * 10 * 10 * amount,
        toAddress: new TonWeb.utils.Address(ENV.VITE_ERC_TO_FROM_ADDRESS /* 收款地址，这是俺的地址*/),
        responseAddress: new TonWeb.utils.Address(fromAddress),
        forwardPayload:comment //负载评论
    }

    console.log('🚧 jettonWallet.createTransferBody', jettonBody)
    //TonWeb.utils.bytesToBase64(await payload.toBoc())
    // const cell = beginCell()
    //       .storeUint(0, 32) // 写入32个零位以表示后面将跟随文本评论
    //       .storeStringTail(orderId) // 写下我们的文本评论
    //       .endCell();
    let payload = await jettonWallet.createTransferBody(jettonBody)


    let transaction = {
        validUntil: Math.floor(Date.now() / 1000) + 6000, // 6000 秒
        messages: [
            {
                address: jettonMinterAddress.toString(true),
                amount: tonFee,
                payload: TonWeb.utils.bytesToBase64(await payload.toBoc())
            }
        ]
    }
    try {
        return await tonConnectUI.sendTransaction(transaction, {
            modals: 'all',
            notifications: 'all'
        });
    } catch (e) {
        console.error(e);
    }

    return null;
};
